#include "doc_parser.h"

#include <fstream>
#include <sstream>

DocParser::DocParser(std::string path)
        : path_(path)
{}

int DocParser::Parse(std::string &title, std::string &body)
{
    // 读取title
    tinyxml2::XMLDocument doc;
    doc.LoadFile(path_.c_str());
    DFS(doc.RootElement(), "title", title);

    // 读取整个文件
    std::ifstream ifs(path_);
    std::stringstream buf;

    buf << ifs.rdbuf();
    body = buf.str();

    ifs.close();
}

bool DocParser::DFS(tinyxml2::XMLElement *elem, const std::string str, std::string &result)
{
    if (elem == nullptr) {
        return false;
    }

    if (elem->Value() == str) {
        result = elem->GetText();
        return true;
    }

    tinyxml2::XMLElement *node = elem->FirstChildElement();
    while (node != nullptr) {
        if (DFS(node, str, result)) {
            return true;
        }

        node = node->NextSiblingElement();
    }

    return false;
}

